package com.molichuxing.gateway.api.services.impl;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.api.services.VehicleApiService;
import com.molichuxing.gateway.bff.car.entity.request.create.AccidentCaseCreateBffVo;
import com.molichuxing.gateway.bff.car.entity.request.create.AccidentCreateBffVo;
import com.molichuxing.gateway.bff.car.entity.request.create.MaintenanceLogCreateVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentCaseDetailVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentDetailVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentOrderCarInfoVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentPagedVo;
import com.molichuxing.gateway.bff.car.entity.response.CarDeliveryCheckVo;
import com.molichuxing.gateway.bff.car.entity.response.CarDeliveryVo;
import com.molichuxing.gateway.bff.car.entity.response.CarOrderCheckVo;
import com.molichuxing.gateway.bff.car.entity.response.CarViolationDetailAppVo;
import com.molichuxing.gateway.bff.car.entity.response.CarViolationVo;
import com.molichuxing.gateway.bff.car.entity.response.FenceCheckVo;
import com.molichuxing.gateway.bff.car.entity.response.MaintenanceAppNewVo;
import com.molichuxing.gateway.bff.car.entity.response.MaintenanceAppVo;
import com.molichuxing.gateway.bff.car.entity.response.MaintenanceLogAppVo;
import com.molichuxing.gateway.bff.car.entity.response.MaintenanceLogVo;
import com.molichuxing.gateway.bff.car.entity.response.PdiCheckVo;
import com.molichuxing.gateway.bff.car.services.AccidentBffService;
import com.molichuxing.gateway.bff.car.services.CheckBffService;
import com.molichuxing.gateway.bff.car.services.MaintenanceBffService;
import com.molichuxing.gateway.bff.car.services.ViolationBffService;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.redis.TokenUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 15:11 2019/9/19
 * @Modified By:
 **/
@Api(tags = "车辆相关接口")
@RestController
@RequestMapping(value = "/vehicle")
public class VehicleApiServiceImpl extends RootApiService implements VehicleApiService {
    private static final Logger logger = LoggerFactory.getLogger(VehicleApiServiceImpl.class);

	@Resource
	private TokenUtil tokenUtil;

    @Resource
    private AccidentBffService accidentBffService;

    @Resource
    private ViolationBffService violationBffService;

    @Resource
    private MaintenanceBffService maintenanceBffService;

    @Resource
    private CheckBffService checkBffService;

    @Override
    @ApiOperation(value = "事故列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resultType", value = "1:用车中数据（该字段不传值默认为1）  2:查看历史数据  ", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/accident/list")
    public ResponseResult<Paged<AccidentPagedVo>> getCarAccidentAppPage(@RequestParam(required=false) Integer resultType,@RequestParam Integer pageNum,@RequestParam  Integer pageSize) {
        ResponseResult<Paged<AccidentPagedVo>> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.getCarAccidentAppPage(resultType,pageNum,pageSize));
        } catch (Exception e) {
            logger.error("事故列表异常", e);
            result.error("事故列表异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "事故详情")
    @ApiImplicitParam(name = "accidentId", value = "事故id", required = true, dataType = "Integer")
    @GetMapping(value = "/accident/details")
    public ResponseResult<AccidentDetailVo> getAppAccident(@RequestParam Integer accidentId) {
        ResponseResult<AccidentDetailVo> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.getAppAccident(accidentId));
        } catch (Exception e) {
            logger.error("事故详情异常", e);
            result.error("事故详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "结案详情")
    @ApiImplicitParam(name = "accidentId", value = "事故id", required = true, dataType = "Integer")
    @GetMapping(value = "/accident/settle/details")
    public ResponseResult<AccidentCaseDetailVo> getAccidentCaseDetail(@RequestParam Integer accidentId) {
        ResponseResult<AccidentCaseDetailVo> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.getAccidentCaseDetail(accidentId));
        } catch (Exception e) {
            logger.error("结案详情异常", e);
            result.error("结案详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询用户所有在用车中的车辆信息")
    @GetMapping(value = "/accident/licencePlate/list")
    public ResponseResult<List<AccidentOrderCarInfoVo>> getLicencePlateByUser() {
        ResponseResult<List<AccidentOrderCarInfoVo>> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.getLicencePlateByUser());
        } catch (Exception e) {
            logger.error("查询用户所有在用车中的车辆信息异常", e);
            result.error("查询用户所有在用车中的车辆信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "创建事故报备信息")
    @PostMapping(value = "/accident/create")
    public ResponseResult<Boolean> createAccidentCreateBff(@RequestBody AccidentCreateBffVo accidentCreateBffVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.createAccidentCreateBff(accidentCreateBffVo));
        }  catch (BizException e) {
            logger.error("创建事故报备信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        }  catch (Exception e) {
            logger.error("创建事故报备信息异常", e);
            result.error("创建事故报备信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "创建结案信息")
    @PostMapping(value = "/accident/settle/create")
    public ResponseResult<Boolean> createAccidentCaseCreateBff(@RequestBody AccidentCaseCreateBffVo accidentCaseCreateBffVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(accidentBffService.createAccidentCaseCreateBff(accidentCaseCreateBffVo));
        }catch (BizException e) {
            logger.error("创建结案信息异常", e);
            result.error(e.getExceptionCode(),e.getMessage());
        } catch (Exception e) {
            logger.error("创建结案信息异常", e);
            result.error("创建结案信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询违章列表")
    @GetMapping(value = "/violation/list")
    public ResponseResult<List<CarViolationVo> > getCarViolationAppVo() {
        ResponseResult<List<CarViolationVo> > result = new ResponseResult<>();
        try {
            return result.success(violationBffService.getCarViolationAppVo());
        } catch (Exception e) {
            logger.error("查询违章列表异常", e);
            result.error("查询违章列表异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询违章详情")
    @ApiImplicitParam(name = "carId", value = "车辆id", required = true, dataType = "Integer")
    @GetMapping(value = "/violation/info")
    public ResponseResult<CarViolationDetailAppVo> getCarViolationDetailAppVo(@RequestParam Integer carId) {
        ResponseResult<CarViolationDetailAppVo> result = new ResponseResult<>();
        try {
            return result.success(violationBffService.getCarViolationDetailAppVo(carId));
        } catch (Exception e) {
            logger.error("查询违章详情异常", e);
            result.error("查询违章详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询用户拥有车辆数")
    @GetMapping(value = "/car/count")
    public ResponseResult<List<Integer>> getCarViolationCarCount() {
        ResponseResult<List<Integer>> result = new ResponseResult<>();
        try {
            return result.success(violationBffService.getCarViolationCarCount());
        } catch (Exception e) {
            logger.error("查询用户拥有车辆数异常", e);
            result.error("查询用户拥有车辆数异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "创建保养历史信息")
    @PostMapping(value = "/maintenance/log/create")
    public ResponseResult<Boolean> createMaintenanceLog(@RequestBody MaintenanceLogCreateVo maintenanceLogCreateVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.createMaintenanceLog(maintenanceLogCreateVo));
        } catch (Exception e) {
            logger.error("创建保养历史异常", e);
            result.error("创建保养历史异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "校验当前保养信息是否是审核通过状态")
    @ApiImplicitParam(name = "maintenanceLogId", value = "保养历史id", required = true, dataType = "Integer")
    @GetMapping(value = "/maintenance/check/state")
    public ResponseResult<Boolean> checkStateMaintenanceLog(@RequestParam Integer maintenanceLogId) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.checkStateMaintenanceLog(maintenanceLogId));
        } catch (Exception e) {
            logger.error("校验当前保养信息是否是审核通过状态异常", e);
            result.error("校验当前保养信息是否是审核通过状态异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "保养历史详情")
    @ApiImplicitParam(name = "maintenanceLogId", value = "保养历史id", required = true, dataType = "Integer")
    @GetMapping(value = "/maintenance/details")
    public ResponseResult<MaintenanceLogVo> maintenanceLogDetail(@RequestParam Integer maintenanceLogId) {
        ResponseResult<MaintenanceLogVo> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.maintenanceLogDetail(maintenanceLogId));
        } catch (Exception e) {
            logger.error("保养历史详情异常", e);
            result.error("保养历史详情异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "保养列表")
    @ApiImplicitParams({
    	    @ApiImplicitParam(name = "resultType", value = "1:用车中数据（该字段不传值默认为1）  2:查看历史数据  ", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/maintenance/list")
    public ResponseResult<MaintenanceAppVo> getMaintenanceAppVoPage(@RequestParam(required=false) Integer resultType,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        ResponseResult<MaintenanceAppVo> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.getMaintenanceAppVoPage(resultType,pageNum,pageSize));
        } catch (Exception e) {
            logger.error("保养列表异常", e);
            result.error("保养列表异常");
        }
        return result;
    }
    
    @Override
    @ApiOperation(value = "保养列表（new）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/maintenance/new/list")
    public ResponseResult<MaintenanceAppNewVo> getMaintenanceAppVoPageNew(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        ResponseResult<MaintenanceAppNewVo> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.getMaintenanceAppVoPageNew(pageNum,pageSize));
        } catch (Exception e) {
            logger.error("保养列表（new）异常", e);
            result.error("保养列表（new）异常");
        }
        return result;
    }
    
    @Override
    @ApiOperation(value = "保养列表（历史数据）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/maintenance/history/list")
    public ResponseResult<Paged<MaintenanceLogAppVo>> getMaintenanceLogAppVoPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        ResponseResult<Paged<MaintenanceLogAppVo>> result = new ResponseResult<>();
        try {
            return result.success(maintenanceBffService.getMaintenanceLogAppVoPage(pageNum,pageSize));
        } catch (Exception e) {
            logger.error("保养列表（历史数据）", e);
            result.error("保养列表（历史数据）");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据订单号查询验车报告")
    @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long")
    @GetMapping(value = "/check/order/confirm")
    public ResponseResult<PdiCheckVo> getCheckReport(@RequestParam Long orderCode) {
        ResponseResult<PdiCheckVo> result = new ResponseResult<>();
        try {
            return result.success(checkBffService.getCheckReport(orderCode));
        } catch (Exception e) {
            logger.error("根据订单号查询验车报告异常", e);
            result.error("根据订单号查询验车报告异常");
        }
        return result;
    }

	// @Override
	// @ApiOperation(value = "新建交接单(大屏)")
	// @PostMapping(value = "/check/create")
	// public ResponseResult<Boolean> createCheckVo(@RequestHeader(value =
	// "deviceNum", required = true) String deviceNum,
	// @RequestBody CheckCreateBffVo checkCreateBffVo) {
	// ResponseResult<Boolean> result = new ResponseResult<>();
	// try {
	// checkCreateBffVo.setDeviceNum(deviceNum);
	// return result.success(checkBffService.createCheckVo(checkCreateBffVo));
	// }catch (BizException e) {
	// logger.error("[createCheckVo]新建交车单异常:", e);
	// result.error(e.getExceptionCode() == null ?
	// ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
	// e.getMessage());
	// }catch (Exception e) {
	// logger.error("[createCheckVo]新建交车单异常", e);
	// result.error("新建交车单异常");
	// }
	// return result;
	// }

    @Override
	@ApiOperation(value = "车辆当前里程")
    @ApiImplicitParam(name = "vin", value = "VIN", required = true, dataType = "String")
	@GetMapping(value = "/current/mileage")
    public ResponseResult<Integer> getMileageByVin(@RequestParam String vin) {
        ResponseResult<Integer> result = new ResponseResult<>();
        try {
            return result.success(checkBffService.getMileageByVin(vin));
		} catch (BizException e) {
			logger.error("[getMileageByVin]获取车辆当前里程异常", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[getMileageByVin]获取车辆当前里程异常", e);
			result.error("获取车辆当前里程异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "交接单预览-车辆和订单信息(大屏)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "carId", value = "车辆id", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/check/order/info")
    public ResponseResult<CarOrderCheckVo> getCarOrderCheckVo(@RequestParam Long orderCode, @RequestParam Integer carId) {
        ResponseResult<CarOrderCheckVo> result = new ResponseResult<>();
        try {
            return result.success(checkBffService.getCarOrderCheckVo(orderCode,carId));
        }catch (Exception e) {
            logger.error("[getCarOrderCheckVo]交接单预览-车辆和订单信息(大屏)异常", e);
			result.error("交接单预览-车辆和订单信息(大屏)异常");
        }
        return result;
    }

    @Override
	@ApiOperation(value = "提车交付车辆列表")
    @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long")
    @GetMapping(value = "/delivery/list")
    public ResponseResult<List<CarDeliveryVo>> getDeliveryCarList(@RequestParam Long orderCode) {
        ResponseResult<List<CarDeliveryVo>> result = new ResponseResult<>();
        try {
            return result.success(checkBffService.getDeliveryCarList(orderCode));
        } catch (BizException e) {
            logger.error("[getDeliveryCarList]交付车辆列表异常", e);
            result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
                    e.getMessage());
        } catch (Exception e) {
            logger.error("[getDeliveryCarList]交付车辆列表异常", e);
            result.error("交付车辆列表异常");
        }
        return result;
    }


	@Override
	@ApiOperation(value = "还车交付车辆信息")
	@ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long")
	@GetMapping(value = "/return/info")
	public ResponseResult<List<CarDeliveryVo>> getReturnCar(
			@RequestHeader(value = "token", required = true) String token,
			@RequestHeader(value = "deviceNum", required = true) String deviceNum, @RequestParam Long orderCode) {
		ResponseResult<List<CarDeliveryVo>> result = new ResponseResult<>();
		try {
			// 根据token获取用户信息
			UserVo user = tokenUtil.getUser(token);
			CarDeliveryVo carDeliveryVo = checkBffService.getReturnCar(orderCode, deviceNum, user.getUserId());
			
			result.success(Arrays.asList(carDeliveryVo));
		} catch (BizException e) {
			logger.error("[getReturnCar]查询还车交付车辆信息失败:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[getReturnCar]查询还车交付车辆信息异常:", e);
			result.error("查询还车交付车辆信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "验证车辆是否在门店围栏")
	@ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long")
	@GetMapping(value = "/fence/check")
	public ResponseResult<FenceCheckVo> fenceCheck(@RequestHeader(value = "token", required = true) String token,
			@RequestHeader(value = "deviceNum", required = true) String deviceNum, @RequestParam Integer carId) {
		ResponseResult<FenceCheckVo> result = new ResponseResult<>();
		try {
			result.success(checkBffService.getFenceCheck(carId, deviceNum));
		} catch (BizException e) {
			logger.error("[fenceCheck]验证车辆是否在门店围栏失败:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[fenceCheck]验证车辆是否在门店围栏异常:", e);
			result.error("验证车辆是否在门店围栏异常");
		}
		return result;
	}

	@ApiOperation(value = "交付车辆检验")
	@ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long")
	@GetMapping(value = "/delivery/check")
	@Override
	public ResponseResult<CarDeliveryCheckVo> carDeliveryCheck(
			@RequestHeader(value = "token", required = true) String token,
			@RequestHeader(value = "deviceNum", required = true) String deviceNum, @RequestParam Integer carId) {
		ResponseResult<CarDeliveryCheckVo> result = new ResponseResult<>();
		try {
			result.success(checkBffService.getCarDeliveryCheck(carId, deviceNum));
		} catch (BizException e) {
			logger.error("[carDeliveryCheck]交付车辆检验失败:", e);
			result.error(e.getExceptionCode() == null ? ResponseCodeEnum.UNKNOWN_ERROR.getCode() : e.getExceptionCode(),
					e.getMessage());
		} catch (Exception e) {
			logger.error("[carDeliveryCheck]交付车辆检验异常:", e);
			result.error("交付车辆检验异常");
		}
		return result;
	}
}
